from coresales.models import Product, ProductDetail
from goodsForSales.settings import MEDIA_ROOT
import datetime

ABSOLUTE_PATH_PRODUCTS= MEDIA_ROOT + 'products/'

from xml.etree.ElementTree import Element, SubElement, tostring, ElementTree
        
class XmlProducts:
        
        def create(self):
            products = Element('products')
            for productEntity in Product.objects.filter(public=True).order_by('code'):
                #code="2963" price="5.00" name="Servilletero calado simple" countOfVisitors="0" lastPublication=
                product = SubElement(products, 'product', {'code':str(productEntity.code),
                                                           'name':productEntity.name,
                                                           'countOfVisitors':str(productEntity.countOfVisitors),
                                                           'lastPublication':str(productEntity.lastPublication),
                                                           'price':str(productEntity.price)})
                #title="Servilletero calado simple" description="Servilletero calado simple"
                SubElement(product, 'photo', {'title':productEntity.photo.title,'description':productEntity.photo.description})
                attributes= SubElement(product, 'attributes')
                #name="Usos"
                for productDetail in ProductDetail.objects.filter(product__code=productEntity.code):
                    SubElement(attributes, 'attribute', {'name':productDetail.attribute.name,'value':productDetail.value})
                    
            
            print tostring(products)
            now = datetime.datetime.now()
            xmlFile = open(ABSOLUTE_PATH_PRODUCTS +"/products-%s.xml"%now.strftime("%Y-%m-%d"), 'w')
            ElementTree(products).write(xmlFile, method='xml')
            xmlFile.close()

if __name__ == '__main__':
    
    XmlProducts().create()
    
    
    pass